package com.opencloud.tenant.admin.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.opencloud.base.client.constants.BaseConstants;
import com.opencloud.base.client.model.entity.BaseRole;
import com.opencloud.common.model.ResultBody;
import com.opencloud.common.security.OpenAuthority;
import com.opencloud.common.security.OpenSecurityConstants;
import com.opencloud.common.security.OpenUserDetails;
import com.opencloud.common.security.oauth2.client.OpenOAuth2ClientProperties;
import com.opencloud.tenant.admin.api.service.feign.BaseTenantServiceClient;
import com.opencloud.tenant.admin.api.service.feign.SysUserServiceClient;
import com.opencloud.tenant.client.enums.SysUserTypeEnum;
import com.opencloud.tenant.client.model.SysUserAccount;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * Security用户信息获取实现类
 *
 * @author liuyadu
 */
@Slf4j
@Service("userDetailService")
public class UserDetailsServiceImpl implements UserDetailsService {

//    @Autowired
//    private BaseUserServiceClient baseUserServiceClient;
    @Autowired
    private SysUserServiceClient sysUserServiceClient;
    @Autowired
    private OpenOAuth2ClientProperties clientProperties;
    @Autowired
    private BaseTenantServiceClient baseTenantServiceClient;

    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        ResultBody<SysUserAccount> resp = sysUserServiceClient.userLogin(username);
        SysUserAccount account = resp.getData();
        if (account == null || account.getAccountId() == null) {
            throw new UsernameNotFoundException("系统用户 " + username + " 不存在!");
        }
        System.out.println("tenant admin =========UserDetailsServiceImpl.loadUserByUsername 当前登录用户的信息"+ JSON.toJSONString(account));
        String domain = account.getDomain();
        Long accountId = account.getAccountId();
        Long userId = account.getUserId();
        String password = account.getPassword();
        String nickName = account.getNickName();
        String avatar = account.getAvatar();
        String accountType = account.getAccountType();
        boolean accountNonLocked = account.getStatus().intValue() != BaseConstants.ACCOUNT_STATUS_LOCKED;
        boolean credentialsNonExpired = true;
        boolean enabled = account.getStatus().intValue() == BaseConstants.ACCOUNT_STATUS_NORMAL ? true : false;
        boolean accountNonExpired = true;
        OpenUserDetails userDetails = new OpenUserDetails();
        userDetails.setTenantId(account.getTenantId());
        userDetails.setDomain(domain);
        userDetails.setAccountId(accountId);
        userDetails.setUserId(userId);
        userDetails.setUsername(username);
        userDetails.setPassword(password);
        userDetails.setNickName(nickName);
        //如果用户是租户默认管理员，权限读取租户的角色
        //判断当前登录用户的类型，如果是系统管理员就查询租户的角色
        // 用户角色列表
        List<Map> roles = Lists.newArrayList();
        // 用户权限列表
        List<OpenAuthority> authorities = Lists.newArrayList();
        if (SysUserTypeEnum.ADMIN.getCode().equals(account.getUserType())){

            ResultBody<List<BaseRole>> listResultBody =  baseTenantServiceClient.getRolesByTenantId(account.getTenantId());

            List<BaseRole> baseRoleList = listResultBody.getData();

            if (baseRoleList != null) {
                for (BaseRole role : baseRoleList) {
                    Map roleMap = Maps.newHashMap();
                    roleMap.put("roleId", role.getRoleId());
                    roleMap.put("roleCode", role.getRoleCode());
                    roleMap.put("roleName", role.getRoleName());
                    // 用户角色详情
                    roles.add(roleMap);
                    // 加入角色标识
                    OpenAuthority authority = new OpenAuthority(role.getRoleId().toString(), OpenSecurityConstants.AUTHORITY_PREFIX_ROLE + role.getRoleCode(), null, "role");
                    authorities.add(authority);
                }
            }
            account.setAuthorities(authorities);
        }
        userDetails.setAuthorities(account.getAuthorities());
        userDetails.setAvatar(avatar);
        userDetails.setAccountId(accountId);
        userDetails.setAccountNonLocked(accountNonLocked);
        userDetails.setAccountNonExpired(accountNonExpired);
        userDetails.setAccountType(accountType);
        userDetails.setCredentialsNonExpired(credentialsNonExpired);
        userDetails.setEnabled(enabled);
        userDetails.setClientId(clientProperties.getOauth2().get("tenant").getClientId());
        return userDetails;
    }
}
